package merge

import (
	"context"
	"gitee.com/kmyss/gf-ex/yscmd"
	"gitee.com/kmyss/gf-ex/yslog"
	"gitee.com/kmyss/ys-cli/internal/cmd/git/bundle"
	"gitee.com/kmyss/ys-cli/internal/model"
	"gitee.com/kmyss/ys-cli/internal/service"
	"github.com/gogf/gf/v2/frame/g"
)

type Builder struct {
	yscmd.CommandBuilderCore
}

func (b *Builder) Init(ctx context.Context) {
	b.CommandBuilderCore.Init(ctx)
	b.C.Use = "bundle-merge"
	b.C.Short = "将离线版本包进行主分支合并"
	b.C.Long = `
    合并分支到主分支`

	b.C.Run = run
	b.addFlag()
}

func (b *Builder) addFlag() {
	b.SetFlags(
		&bundle.FlagBundlePathBuilder{},
	)
	yscmd.SetDefaultFlag(b)
}

func run(c *yscmd.Command) {
	gitSrv := service.Git()

	// 判断能不能 PULL
	ok, err := gitSrv.CanPull(c.Context())
	if !ok || err != nil {
		if err != nil {
			yslog.Error(err)
		}
		yscmd.CmdWait(c.Context())
		return
	}

	// 生成配置文件
	cfg := &model.BundleConfigInput{}
	cfg.Path = bundle.FlagBundlePath(c.Context()).Get()
	if g.IsEmpty(cfg.Path) {
		_ = cfg.GetPath()
	}

	err = gitSrv.BundleMerge(c.Context(), cfg)
	if err != nil {
		yslog.Error(err)
		yscmd.CmdWait(c.Context())
		return
	}

	yscmd.TimeToCloseShell(c.Context(), 2)
}

func BundleMerge(ctx context.Context) *yscmd.Command {
	c := &Builder{}
	c.Init(ctx)
	return c.Command()
}
